package top.kent90.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.kent90.service.RedisService;

/**
 *  处理登录的拦截器
 * @author Administrator
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Reference
	RedisService redisService;

	/**
	 * 预处理，先于controller执行，返回true为放行请求，再到下一个拦截器，
	 * 如果没有可执行的拦截器，再到controller进行处理
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("我是preHandle");
		//使用redis的指定缓存时间来控制用户的登录及超时
		HttpSession session = request.getSession();
		if (redisService.hasKey(session.getId())){
			//如果存在这个回话id的用户，就刷新时间，
			redisService.expire(session.getId(), 600);
			return true;
		}else {
			request.setAttribute("msg", "请登录！");
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request,response);
			return false;
		}

		/*
		//控制是否有用户登录
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("UserInfo");
		if(obj==null) {
			request.setAttribute("msg", "请登录！");
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request,response);
			return false;
		}
		return true;*/
	}

	/**
	 *    怎么处理ajax请求
	 */
	@Override
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView model)
			throws Exception {
		/*HttpSession session = request.getSession();
		Object obj = session.getAttribute("UserInfo");
		if(obj==null) {
			model.addObject("msg", "请登录！");
			model.setViewName("../../index");
		}*/
	}

	/**
	 * controller处理完成之后，再经过此方法
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
		System.out.println("我是afterCompletion");
	}
}